package com.xsj.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class Capt {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Capt() {
    }

    public String generateCaptcha(HttpServletResponse response) {
        String uniqueKey = IdUtil.fastSimpleUUID();
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String code = lineCaptcha.getCode();

        try {
            String redisKey = "captcha:" + uniqueKey;
            this.redisTemplate.opsForValue().set(redisKey, code, 5L, TimeUnit.MINUTES);
            response.setContentType("image/png");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0L);
            response.setHeader("Access-Control-Expose-Headers", "X-Captcha-Key");
            response.setHeader("Access-Control-Allow-Headers", "X-Captcha-Key");
            response.setHeader("X-Captcha-Key", uniqueKey);
            lineCaptcha.write(response.getOutputStream());
            return uniqueKey;
        } catch (IOException var6) {
            throw new RuntimeException("生成验证码失败", var6);
        }
    }

    public boolean verifyCaptcha(String key, String inputCaptcha) {
        if (key != null && !key.isEmpty() && inputCaptcha != null && !inputCaptcha.isEmpty()) {
            String redisKey = "captcha:" + key;
            System.out.println("前端传来的验证码key" + redisKey);
            String storedCaptcha = (String)this.redisTemplate.opsForValue().get(redisKey);
            if (storedCaptcha == null) {
                return false;
            } else if (storedCaptcha.equalsIgnoreCase(inputCaptcha)) {
                this.redisTemplate.delete(redisKey);
                return true;
            } else {
                return false;
            }
        } else {
            System.out.println("验证码为空");
            return false;
        }
    }
}
